package com.finalhomework.dms.controller;

import com.finalhomework.dms.dao.DorRepository;
import com.finalhomework.dms.dao.StudentRepository;
import com.finalhomework.dms.entities.Dormitory;
import com.finalhomework.dms.entities.Students;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@Controller
public class StudentController {


    @Autowired
    DorRepository dorRepository;
    @Autowired
    StudentRepository studentRepository;
    @RequestMapping("/students")
    public String list(Model model){
        List<Dormitory> aDormitory=dorRepository.findAll();
        model.addAttribute("aDormitory",aDormitory);
        List<Students> aStudent=studentRepository.findAll();
        model.addAttribute("aStudent",aStudent);
        return "student/list";
    }

    @GetMapping("/studentAdd")
    public String toAddStudents(Model model){
        Students aStudent=new Students();
        List<Dormitory> aDormitory=dorRepository.findAll();
        for (int i = 0; i < aDormitory.size(); i++) {
            if ((aDormitory.get(i).getHabitableNum())==(aDormitory.get(i).getResidentNumber())) {
                aDormitory.remove(i);
                i--;
            }
        }
        model.addAttribute("aStudent",aStudent);
        model.addAttribute("aDormitory",aDormitory);

        return "student/addStudents";
    }
    @PostMapping("/students/save")
    public String createStudents(Model model, Students students,@RequestParam long dormitoryId){

        students.setDormitory(dorRepository.getDormitoryById(dormitoryId));
        dorRepository.getDormitoryById(dormitoryId).setHabitableNum((dorRepository.getDormitoryById(dormitoryId).getHabitableNum()+1));
        studentRepository.save(students);
        return "redirect:/studentAdd";
    }

    @GetMapping("/bStudent/{id}")
    public String toUpdateStudent(@PathVariable("id")long id,Model model){
        Students students=studentRepository.getStudentsById(id);
        model.addAttribute("stu",students);

        List<Dormitory> aDor=dorRepository.findAll();
        model.addAttribute("dor",aDor);

        return "student/updateStudents";

    }

    @PostMapping("/updateStu")
    public String updateStudent(Students students){
        studentRepository.save(students);
        return "redirect:/students";

    }

    @GetMapping("/delstu/{id}")
    public String deleteStudent(@PathVariable("id")int id){
        Students students=studentRepository.getStudentsById(id);
        students.getDormitory().setHabitableNum(students.getDormitory().getHabitableNum()-1);
        studentRepository.deleteById(id);
        return "redirect:/students";
    }

}
